package com.dog.modules.file.service.impl;

import cn.hutool.core.lang.Assert;
import com.dog.framework.core.exception.FileException;
import com.dog.modules.file.model.SysFileUploadVO;
import com.dog.modules.file.service.OssService;
import com.dog.modules.file.utils.FileUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @author haoxr
 * @since 2023/6/2
 */
@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "local")
@ConfigurationProperties(prefix = "oss.local")
@RequiredArgsConstructor
@Data
public class LocalOssService implements OssService {

    private String domain;
    /**
     * 本地存储路径
     */
    private String path;
    /**
     * 资源起始路径
     */
    private String prefix;


    /**
     * 上传文件
     *
     * @param file 表单文件对象
     * @return
     */
    @SneakyThrows
    @Override
    public SysFileUploadVO uploadFile(MultipartFile file) {
        SysFileUploadVO sysFileUploadVO = new SysFileUploadVO();
        String newPathFile = FileUtils.getPath(file.getOriginalFilename());

        try {
            File localFile = new File(path + File.separator + prefix + File.separator + newPathFile);

            // 没有目录，则自动创建目录
            File parent = localFile.getParentFile();
            if (parent != null && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("目录 '" + parent + "' 创建失败");
            }

            FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(localFile.toPath()));
        } catch (Exception e) {
            throw new FileException("上传文件失败：", e.getStackTrace());
        }

        String fileUrl = domain + File.separator + path + File.separator + prefix + File.separator + newPathFile;

        sysFileUploadVO.setUrl(fileUrl);
        sysFileUploadVO.setName(file.getOriginalFilename());
        sysFileUploadVO.setSize(file.getSize());
        sysFileUploadVO.setPlatform("local");

        return sysFileUploadVO;
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件路径
     *
     * @return
     */
    @SneakyThrows
    @Override
    public boolean deleteFile(String fileUrl) {
        Assert.notBlank(fileUrl, "删除文件路径不能为空");
        File localFile = new File(path + File.separator + prefix + File.separator+ fileUrl );
        localFile.delete();
        return true;
    }
}


